package com.rw.engine.asynchronous.aspect;

import com.rw.engine.asynchronous.anno.AsyncMethod;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 默认投递器
 */
public class DefaultAsyncDeliver implements AsyncDeliver {
    private static final ExecutorService GLOBAL_POOL = Executors.newFixedThreadPool(1);

    private final ExecutorService executorService;

    public DefaultAsyncDeliver(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public DefaultAsyncDeliver() {
        this.executorService = GLOBAL_POOL;
    }

    @Override
    public void deliver(Object target, Method method, Object[] args, AsyncMethod async) {
        // 开启线程
        executorService.submit(() -> submit(target, method, args));
    }

    private void submit(Object target, Method method, Object[] args) {
        try {
            method.invoke(target, args);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}
